package com.mssh.login.util;

import com.mssh.entity.exception.SecretException;
import org.apache.commons.codec.binary.Base64;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 熳殊沙华
 * @Date: 2023/09/20/8:50
 * @Description: Aes加解密工具类
 */
public class AesUtil {

    private static Logger logger = LogManager.getLogger(AesUtil.class);

    /**
     * ASE加密
     * @param data
     * @param key
     * @param iv
     * @return
     */
    public static String encrypt(String data, String key, String iv) throws SecretException {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");    //CBC模式
            int blockSize = cipher.getBlockSize();
            byte[] dataBytes = data.getBytes();
            int plaintextLength = dataBytes.length;
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }
            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);
            return new Base64().encodeToString(encrypted);
        } catch (Exception e) {
            logger.warn("ASE加密异常：" + e);
            throw new SecretException("ASE加密异常");
        }
    }

    /**
     * ASE解密
     * @param data
     * @param key
     * @param iv
     * @return
     * @throws Exception
     */
    public static String desEncrypt(String data, String key, String iv) throws SecretException {
        try {
            byte[] encrypted1 = new Base64().decode(data);
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original);
            return originalString.trim();
        } catch (Exception e) {
            logger.warn("ASE解密异常：" + e);
            throw new SecretException("ASE解密异常");
        }
    }

    /**
     * ASE加密，公用key
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static String encryptWithKey(String data, String key) throws SecretException {
        return encrypt(data, key, key);
    }

    /**
     * ASE解密，公用key
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static String desEncryptWithKey(String data, String key) throws SecretException {
        return desEncrypt(data, key, key);
    }

    /**
     * 生成动态的ase秘钥key
     * @return
     */
    public static String getRandomAseKey(){
        String[] chars = {
                "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F",
                "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
                "W", "X", "Y", "Z", ".", "?", "~", "!", "@", "#", "$", "%", "^", "&", "*"
        };
        String secretKey = "";
        Random random = new Random();
        for(int i = 0; i < 16; i++) {
            int id = random.nextInt(chars.length);
            secretKey += chars[id];
        }
        return secretKey;
    }
}
